package com.yc.blog.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;


import com.yc.blog.bean.AdminInfo;
import com.yc.blog.biz.IBlogInfoBiz;
import com.yc.blog.biz.impl.BlogInfoBizImpl;
import com.yc.blog.util.FileUploadUtil;
import com.yc.blog.util.SessionKeys;

@WebServlet("/blog")
public class BlogInfoController extends BasicController{

private static final long serialVersionUID = -194522302464253435L;

	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String op=request.getParameter("op");
		if("add".equals(op)) {
			add(request,response);
		}else if("upload".equals(op)) {
			upload(request,response);
		}else if("findByPage".equals(op)) {
			findByPage(request,response);
		}else if("findByBid".equals(op)) {
			findByBid(request,response);
		}
    }

	private void findByBid(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String bid = request.getParameter("bid");
		
		IBlogInfoBiz blogInfoBiz=new BlogInfoBizImpl();
		this.send(response, blogInfoBiz.findByBid(bid));
	}

	private void findByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int page = Integer.parseInt(request.getParameter("page"));
		int rows = Integer.parseInt(request.getParameter("rows"));
		
		IBlogInfoBiz blogInfoBiz=new BlogInfoBizImpl();
		this.send(response, blogInfoBiz.findByPage(page, rows));
	}

	private void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
		FileUploadUtil fuu=new FileUploadUtil();
		PageContext pageContext=JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8192, true);
		Map<String,Object> result=new HashMap<String, Object>();
			try {
				Map<String,String> map=fuu.upload(pageContext);
				//以下必须这样写
				String path=map.get("upload");
				result.put("fileName", path.substring(path.lastIndexOf("_")));
				result.put("url","../../"+path);
				result.put("uploaded", 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		//以json格式返回这个结果
			this.send(response, result);
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Object obj=request.getSession().getAttribute(SessionKeys.CURRENTBACKLOGINACCOUNT);
		if(obj==null) {
			this.send(response, -1);
			return;
		}
		int aid=((AdminInfo)obj).getAid();
		String tid=request.getParameter("tid");
		String title=request.getParameter("title");
		String content=request.getParameter("content");
		
		IBlogInfoBiz blogInfoBiz=new BlogInfoBizImpl();
		this.send(response, blogInfoBiz.add(tid, title, content, aid));
	}
}
